<template>
  <div class="app-container">
    <div class="search-container">
      <el-form :model="searchParam" :inline="true" label-width="75px">
        <el-form-item label="计划年月">
          <el-date-picker
            v-model="searchParam.yearMonthPlan"
            type="month"
            placeholder="请输入年月"
            value-format="YYYY-MM"
          />
        </el-form-item>
        <el-form-item label="冷铁名称">
          <el-input
            v-model="searchParam.ironName"
            placeholder="请选择冷铁名称"
            clearable
            readonly
            @click="showWorkOrderSelect"
          >
            <template #append>
              <el-button @click="reset"> 清除 </el-button>
            </template>
          </el-input>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="beforeGetTableList">
            <i-ep-search />
            展示
          </el-button>
        </el-form-item>
      </el-form>
    </div>

    <el-card shadow="never" class="table-container">
      <template #header> </template>

      <!-- 导入计划 -->
      <ImportExcel ref="weekImportRef" />

      <!-- 合计行的id定义为-999，当表格返回-999时，没有点击事件，展示合计行内容 -->

      <!-- objectSpanMethod方法，objectSpanMethod(param, 3, 7)
      参数3 代表三行合并
      参数13 代表从第13 + 1 列开始取消合并 -->

      <el-table
        ref="dataTableRef"
        v-loading="loading"
        element-loading-text="数据准备中，请稍后..."
        :data="tableData"
        highlight-current-row
        border
        @selection-change="handleSelectionChange"
        :span-method="(param) => objectSpanMethod(param, 6, 4)"
        :header-cell-style="{ textAlign: 'center' }"
        @sort-change="onTableSortChanged"
        class="dataTable"
      >
        <!--<el-table-column
          type="selection"
          width="55"
          align="center"
          fixed
          :selectable="selectableStatus"
        />-->
        <el-table-column width="70" label="序号" align="center" fixed>
          <template #default="{ $index, row }">
            <span>{{ $index / 6 + 1 }}</span>
          </template>
        </el-table-column>
        <!--<el-table-column
          label="产品名称"
          prop="materialCode"
          width="200"
          show-overflow-tooltip
          fixed
          align="left"
          class-name="padding012"
        >
          <template #default="{ row }">
            <span
              class="cursor-pointer decoration-underline p-0! can_edit_cell"
              @click="planMaterial(row)"
            >
              {{ row.materialName }}~{{ row.materialCode }}
            </span>
          </template>
        </el-table-column>-->
        <el-table-column
          label="冷铁名称"
          prop="ironName"
          min-width="100"
          align="right"
          class-name="padding012"
        />
        <el-table-column
          label="库存数量"
          prop="stockQuantity"
          min-width="100"
          align="right"
          class-name="padding012"
        >
          <template #default="{ row }">
            <span
              class="cursor-pointer decoration-underline p-0! can_edit_cell"
              v-if="row.id != -999"
              @click="openEditPrompt(row)"
              >{{ row.stockQuantity }}</span
            >
            <span class="text-[13px]" v-else></span>
          </template>
        </el-table-column>
        <el-table-column
          label="需求数量"
          prop="demandQuantity"
          min-width="100"
          align="right"
          class-name="padding012"
        />
        <el-table-column label="数据列" width="110" align="center">
          <template #default="{ $index }">
            <span class="text-[13px]" v-if="($index + 1) % 6 == 1"
              >下线数量</span
            >
            <span class="text-[13px]" v-if="($index + 1) % 6 == 2"
              >A班回收率</span
            >
            <span class="text-[13px]" v-if="($index + 1) % 6 == 3"
              >B班回收率</span
            >
            <span class="text-[13px]" v-if="($index + 1) % 6 == 4"
              >A班回收数量</span
            >
            <span class="text-[13px]" v-if="($index + 1) % 6 == 5"
              >B班回收数量</span
            >
            <span class="text-[13px]" v-if="($index + 1) % 6 == 0"
              >剩余库存数量</span
            >
          </template>
        </el-table-column>
        <el-table-column
          v-for="(dayItem, dayIndex) in intervalDayList"
          :key="dayIndex"
          :label="`${dayItem.date}\n${dayItem.week}`"
          :label-class-name="
            dayItem.week == 0 || dayItem.week == 6 ? 'bg-free' : ''
          "
          min-width="65"
          align="right"
        >
          <template #default="{ row, $index }">
            <div
              :style="{
                backgroundColor:
                  inConsistentOne(row, $index, dayItem) == ''
                    ? ''
                    : inConsistentOne(row, $index, dayItem),
              }"
            >
              <!-- 下线数量 -->
              <div v-if="($index + 1) % 6 == 1" style="height: 25px">
                <span
                  v-if="row.id !== '-999'"
                  class="cursor-pointer cellNumber"
                  @click="
                    openYieldInfo(
                      row.id,
                      '下线数量修改',
                      null,
                      nu1l,
                      row,
                      intervalDayList[dayIndex]
                    )
                  "
                >
                  <div v-for="(item, index) in row.details" :key="index">
                    <span v-if="getMonthAndDay(item.ironDate) === dayItem.date">
                      {{ row.details[index]?.quantity || "" }}
                    </span>
                  </div>
                </span>
              </div>
              <!-- A回收率 -->
              <div v-if="($index + 1) % 6 == 2" style="height: 25px">
                <span v-if="row.id !== '-999'">
                  <div v-for="(item, index) in row.details" :key="index">
                    <span v-if="getMonthAndDay(item.ironDate) === dayItem.date">
                      {{ row.details[index]?.recycleOdds1 || "" }}
                    </span>
                  </div>
                </span>
              </div>
              <!-- B回收率 -->
              <div v-if="($index + 1) % 6 == 3" style="height: 25px">
                <span v-if="row.id !== '-999'">
                  <div v-for="(item, index) in row.details" :key="index">
                    <span v-if="getMonthAndDay(item.ironDate) === dayItem.date">
                      {{ row.details[index]?.recycleOdds2 || "" }}
                    </span>
                  </div>
                </span>
              </div>
              <!-- C回收率 -->
              <div v-if="($index + 1) % 6 == 4" style="height: 25px">
                <span v-if="row.id !== '-999'">
                  <div v-for="(item, index) in row.details" :key="index">
                    <span v-if="getMonthAndDay(item.ironDate) === dayItem.date">
                      {{ row.details[index]?.recycleOdds3 || "" }}
                    </span>
                  </div>
                </span>
              </div>
              <!-- A班回收数量 -->
              <div v-if="($index + 1) % 6 == 5" style="height: 25px">
                <span v-if="row.id !== '-999'">
                  <div v-for="(item, index) in row.details" :key="index">
                    <span v-if="getMonthAndDay(item.ironDate) === dayItem.date">
                      {{ row.details[index]?.groupsIron1 || "" }}
                    </span>
                  </div>
                </span>
              </div>
              <!-- B班回收数量 -->
              <div v-if="($index + 1) % 6 == 6" style="height: 25px">
                <span v-if="row.id !== '-999'">
                  <div v-for="(item, index) in row.details" :key="index">
                    <span v-if="getMonthAndDay(item.ironDate) === dayItem.date">
                      {{ row.details[index]?.groupsIron2 || "" }}
                    </span>
                  </div>
                </span>
              </div>
              <!-- C班回收数量 -->
              <div v-if="($index + 1) % 6 == 7" style="height: 25px">
                <span v-if="row.id !== '-999'">
                  <div v-for="(item, index) in row.details" :key="index">
                    <span v-if="getMonthAndDay(item.ironDate) === dayItem.date">
                      {{ row.details[index]?.groupsIron3 || "" }}
                    </span>
                  </div>
                </span>
              </div>
              <!-- 剩余库存数量 -->
              <div v-if="($index + 1) % 6 == 0" style="height: 25px">
                <span v-if="row.id !== '-999'">
                  <div v-for="(item, index) in row.details" :key="index">
                    <span v-if="getMonthAndDay(item.ironDate) === dayItem.date">
                      {{ row.details[index]?.stockQuantity || "" }}
                    </span>
                  </div>
                </span>
              </div>
            </div>
          </template>
        </el-table-column>
      </el-table>
    </el-card>

    <!-- 下线数量修改 -->
    <plan-iron-yield-info-dialog
      :visible="yieldDialog.visible"
      :title="yieldDialog.title"
      :cellId="yieldDialog.cellId"
      :demandStatus="yieldDialog.demandStatus"
      :endDate="yieldDialog.endDate"
      :begirate="yieldDialog.beginDate"
      :data="yieldDialog.data"
      @reset-table="getTableList(0)"
      :is-readonly="yieldDialog.readvisible"
      @change-visible="changeVisible"
    />

    <!-- 导入失败错误信息弹窗 -->
    <upload-error-table ref="uploadErrorRef" :errorDataList="errorDataList" />

    <!--物料选择-->
    <iron-select
      :visible="selectDialogSELECT.visible"
      @change-visible="changeVisibleSELECT"
      :plantId="searchParam.plantId"
      :brekList="brekList"
    />
  </div>
</template>

<script setup lang="ts">
import {
  SearchInterface,
  TableResultObject,
  ScheduleList,
} from "./utilejs/interface";
import {
  resolveSearchData,
  objectSpanMethod,
  getDaysByMonth,
  selectableStatus,
  inConsistent,
  inConsistentOne,
} from "./utilejs/index";
import { filterOrder, promptValidateNumber } from "@/utils/commonHooks";
import dayjs from "dayjs";
import request from "@/utils/request";
import { useDownload, useDictionary } from "@/utils/useTable";

defineOptions({
  name: "MESMESIRONDEMANDOVERVIEW",
  inheritAttrs: false,
});

// 初始化搜索参数数据
const searchParam = reactive<SearchInterface>({
  ironId: "",
  ironName: "",
  yearMonthPlan: getCurrentDate(),
});

// 点击搜索按钮后被保存的搜索数据
const searchedParam = reactive<SearchInterface>({
  ironId: "",
  ironName: "",
  yearMonthPlan: getCurrentDate(),
});

// 搜索时间变化后处理函数
const intervalDayList = ref<any[]>([]);

// 行复选框选中后处理
const ids = ref<string[]>([]);
const dataTableRef = ref();
// 表格选择
const totalMultipleSelection: any = ref([]);
function handleSelectionChange(selection: TableResultObject[]) {
  // ids.value = selection.map((item: TableResultObject) => item.id);
  totalMultipleSelection.value = selection;
}

// 开始展示逻辑处理
const loading = ref(false);
const tableData = ref([]);
// 点击展示之前
function beforeGetTableList() {
  if (!searchParam.yearMonthPlan) {
    ElMessage.error("请选择计划月");
    return;
  }
  getTableList(1);
}

// 点击展示之后
async function getTableList(isReset = 0) {
  // isReset为 1 加载刷新、0 无感知刷新
  if (isReset === 1) {
    dataTableRef.value.setScrollTop(0);
    loading.value = true;
  }
  const { data }: any = await request({
    url: "/mes/mesirondemandoverview/getList",
    method: "post",
    data: isReset === 0 ? toRaw(searchedParam) : toRaw(searchParam),
  }).catch(() => {});
  // 储存被搜索条件
  Object.assign(searchedParam, {
    ...toRaw(searchParam),
  });
  // 时间处理
  intervalDayList.value = getDaysByMonth(searchParam.yearMonthPlan);
  // 数据处理
  tableData.value = resolveSearchData(data);
  // if (data.length > 0) {
  //   let warning = "";
  //   data.forEach((item) => {
  //     warning += item.ironName + "：";
  //     let stocks = item.details.map((i: any) => i.stock);
  //     console.log("stocks", stocks.includes(true))
  //     if (!stocks.includes(true)) {
  //       warning = "";
  //     } else {
  //       item.details.forEach((item1) => {
  //         if (item1?.stock) {
  //           warning += getMonthAndDay(item1.ironDate) + ",";
  //         }
  //       });
  //       warning += "\n";
  //     }
  //   });
  //   if (warning) {
  //     ElMessageBox.confirm(warning + "冷铁不足", "提示", {
  //       showCancelButton: false,
  //       confirmButtonText: "已知晓",
  //       cancelButtonText: "取消",
  //       type: "warning",
  //     }).then(() => {});
  //   }
  // }
  loading.value = false;
}

// 监听表格后台排序方法
const initParam = reactive({ sort: {} });
function onTableSortChanged(column: any) {
  const { prop, order } = column;
  initParam.sort = {
    column: prop,
    orderBy: filterOrder(order),
  };

  getTableList(1);
}

function changeVisible(value: boolean) {
  yieldDialog.visible = value;
  if (!value) {
    yieldDialog.data = {};
    yieldDialog.cellId = "";
    detailData = {};
  }
}

// 下线数量对应数据
let detailData = reactive({
  id: "",
  oId: "",
  ironId: "",
  ironName: "",
  quantity: "",
  ironDate: "",
});
const updateColour = (row?: any, day) => {
  let one = null;
  row.details.forEach((item) => {
    if (getMonthAndDay(item.ironDate) === day.date) {
      one = item;
    }
  });
  if (one?.status === 1) {
    ElMessageBox.confirm("是否确认?", "警告", {
      confirmButtonText: "确认",
      cancelButtonText: "取消",
      type: "warning",
    })
      .then(async () => {
        one.status = 2;
        const res: any = await request({
          url: `/mes/mesplanmonthrequire/save`,
          method: "post",
          data: one,
        });
        if (res.code == 200) {
          ElMessage({
            type: "success",
            message: "确认成功",
          });
          getTableList(1);
        }
      })
      .catch(() => {});
  }
};

// 反馈信息确认弹窗及操作逻辑
const yieldDialog = reactive<any>({
  visible: false,
  readvisible: false,
  title: "",
  data: {},
  endDate: "",
  beginDate: "",
  cellId: "",
  demandStatus: null,
});
const openYieldInfo = (
  cellId = "",
  title = "",
  demandStatus = null,
  contentNumber = null,
  row: any,
  day
) => {
  console.log("day", day.date);
  // detailData.ironId = row.ironId;
  // detailData.ironName = row.ironName;
  row.details.forEach((item) => {
    if (getMonthAndDay(item.ironDate) === day.date) {
      detailData = item;
      // detailData.quantity = item.quantity;
    }
  });
  if (detailData?.status === 1) {
    ElMessage.error("日计划已生成，不可编辑！");
    return;
  }
  if (
    new Date(mesdayplan()) >
    new Date(row.yearMonthPlan + "-" + day.date.slice(3, 5))
  ) {
    ElMessage.error("只能修改当天和当天以后数据！");
    return;
  }
  detailData.oId = row.id;
  detailData.ironDate = row.yearMonthPlan + "-" + day.date.slice(3, 5);
  const object = {
    visible: true,
    title: title,
    beginDate: dayjs(searchedParam.yearMonthPlan)
      .startOf("month")
      .format("YYYY-MM-DD"),
    endDate: dayjs(searchedParam.yearMonthPlan)
      .endOf("month")
      .format("YYYY-MM-DD"),
    cellId: cellId,
    demandStatus: demandStatus,
    contentNumber: contentNumber == null ? "" : contentNumber,
    data: detailData,
  };
  console.log(object);
  Object.assign(yieldDialog, { ...object });
};
// 获取当前日期yyyymmdd
function mesdayplan() {
  const now = new Date();
  const year = now.getFullYear();
  const month = ("0" + (now.getMonth() + 1)).slice(-2);
  const day = ("0" + now.getDate()).slice(-2);
  return year + "-" + month + "-" + day;
}
// 导入计划
const weekImportRef = ref();
const uploadErrorRef = ref();
const errorDataList = ref([]);
async function weekImportApiFunc(formdata: FormData, config: any) {
  await request
    .post("/srm/srmmaterialdemand/upload", formdata, config)
    .then((res: any) => {
      weekImportRef.value.resCode = res.code;
      if (res.code === 300) {
        errorDataList.value = res.data;
        uploadErrorRef.value.errorBox = true;
      }
    })
    .catch((e) => {
      weekImportRef.value.resCode = 500;
    });
}
const weekBatchImport = () => {
  let params = {
    title: "导入计划",
    tempApi: "", //模板下载
    importApi: weekImportApiFunc, // 导入
    getTableList: getTableList, // 成功后回调
    isShowTemp: false,
    otherParams: {
      yearMonthPlan: searchedParam.yearMonthPlan,
    },
  };
  weekImportRef.value.acceptParams(params);
};

const openEditPrompt = (row: any) => {
  ElMessageBox.prompt("库存数量", row.materialName, {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    customClass: "prompt_custom",
    closeOnClickModal: false,
    inputValue: String(row.stockQuantity),
    inputValidator: (value: string) => quantity(value),
  })
    .then(async ({ value }) => {
      row.stockQuantity = value;
      const res = await request({
        url: "/mes/mesirondemandoverview/save",
        method: "post",
        data: row,
      });
      if (res.code === 200) {
        ElMessage({
          type: "success",
          message: `修改成功`,
        });
        getTableList(1);
      }
    })
    .catch(() => {});
};
function quantity(value: any) {
  if (isNaN(parseFloat(value)) && isFinite(value)) {
    return "请输入数字";
  } else if (!/^[+-]?\d*(\.\d*)?(e[+-]?\d+)?$/.test(value)) {
    return "请输入数字";
  } else if (!/^[+-]?\d+?(e[+-]?\d+)?$/.test(value)) {
    return "请输入整数";
  } else {
    return true;
  }
}
function getMonthAndDay(date: any) {
  let month = date.slice(5, 7);
  let day = date.slice(8, 10);
  return month + "/" + day;
}
//产品选择
const showWorkOrderSelect = () => {
  selectDialogSELECT.value.visible = true;
};
//选择物料弹窗
const selectDialogSELECT = ref({
  visible: false,
});
const changeVisibleSELECT = (val: boolean, data: any) => {
  selectDialogSELECT.value.visible = val;
  if (data) {
    searchParam.ironId = data.id;
    searchParam.ironName = data.name;
  }
};
// 回显的数据
const brekList = ref([]);

// 重置搜索条件
const reset = () => {
  searchParam.ironId = "";
  searchParam.ironName = "";
};
// 获取当前年月YYYY-MM
function getCurrentDate() {
  const today = new Date();
  let year = today.getFullYear();
  let month = (today.getMonth() + 1).toString().padStart(2, "0");
  let day = today.getDate().toString().padStart(2, "0");
  return year.toString() + "-" + month;
}
</script>

<style lang="scss" scoped>
// 所有表格样式
:deep(.dataTable) {
  .el-table__body td.el-table__cell {
    padding: 0;
    .can_edit_cell:hover {
      color: #409eff !important;
    }
  }
  .cell {
    padding: 0;
    white-space: pre-wrap;
  }
  .padding012 .cell {
    padding: 0 12px !important;
  }
  td.el-table__cell .cell > :first-child {
    padding: 3px 12px;
  }

  .el-scrollbar__wrap {
    max-height: calc(100vh - 342px);
    overflow-y: scroll;
  }

  .seltAllbtnDis .cell {
    visibility: hidden;
  }
  .el-table__empty-block {
    height: 120px !important;
  }
}

:deep(.el-table--border th.bg-free) {
  background-color: rgb(239.8, 248.9, 235.3) !important;
}

// 红色标识
.c-red-font {
  background-color: #fef1f1 !important;
  span {
    // color: lightcoral;
    color: brown !important;
  }
}

// 绿色标识
.c-green {
  background: #55efc4 !important;
  span {
    color: #2f4f4f !important;
  }
}

.cellNumber:hover {
  text-decoration: underline;
}
</style>
